import * as x from './data';
import _ from 'lodash';
import crypto from 'crypto';
import moment from 'moment';

const saltChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const saltCharsLen = saltChars.length;
const globalSalt = 'emr2016';//WARNING:一旦实施就把不要更改了;
const generateSalt = (l = 6) => {
    const arr = [];
    const maxLen = saltCharsLen - 1;
    for (let i = 0; i < l; i++) {
        arr.push(saltChars[_.random(0, maxLen)]);
    }
    return arr.join('');
};
const generatePw = (pw, salt) => {
    const md5 = crypto.createHash('md5');
    md5.update([_.toLower(pw), salt].join(globalSalt));
    return md5.digest('hex');
};

export function get(type, query) {
    return x.get(type, query);
}

export function save(data) {
    const {Password, Password2} = data;
    if (Password !== undefined) {
        if (Password !== Password2) {
            throw '两次密码不一致';
        }
        data = _.omit(data, 'Password2');
        data.Salt = generateSalt();
        data.Password = generatePw(data.Password, data.Salt);
    }
    return x.save(data);
}

export function del(id) {
    return x.del(id);
}

export function login({username, password}) {
    return x.find({UserName: username}).then(user => {
        if (!user) {
            throw '用户不存在';
        }
        if (user.Status !== 1) {
            throw '用户未启用';
        }

        if (!user.Password) {
            throw '用户信息不完善';
        }

        const pw = generatePw(password, user.Salt);
        if (pw !== user.Password) {
            throw '鉴权失败';
        }
        const now = moment();
        if (user.DateStart && moment(user.DateStart) > now) {
            throw '授权还没有生效';
        }
        if (user.DateEnd && moment(user.DateEnd) < now) {
            throw '授权已经失效';
        }
        return _.pick(user, 'Id,UserName,Name,AuthData'.split(','));
    });
}
//校验密码
export function checkpwd(data) {
    const {username, password} = data;
    if (!username) throw '校验用户名不能为空';
    if (!password) throw '校验密码不能为空';
    return x.find({UserName: username}).then(user => {
        if (!user) {
            throw '用户不存在';
        }
        if (user.Status !== 1) {
            throw '用户未启用';
        }

        if (!user.Password) {
            throw '用户信息不完善';
        }

        const pw = generatePw(password, user.Salt);
        if (pw !== user.Password) {
            throw '旧密码输入不正确';
        }
        return true;
    });
}

export function changepwd(data) {
    const {UserName, oldPassword, newPassword, confirmPassword} = data;
    //console.log('data:', data);
    if (!oldPassword) throw '旧密码不能为空';
    if (newPassword !== undefined) {
        if (newPassword !== confirmPassword) {
            throw '新密码和确认密码不一致';
        }
        return checkpwd({username: UserName, password: oldPassword}).then((res) => {
            const success = res;
            if (success) {
                data = _.omit(data, 'oldPassword');
                data = _.omit(data, 'newPassword');
                data = _.omit(data, 'confirmPassword');
                data.Salt = generateSalt();
                data.password = generatePw(newPassword, data.Salt);
                return x.save(data);
            }
        });
    }
}
